package com.yule.controller;

import com.yule.config.DynamicDataSourceContext;
import com.yule.flow.home.FlowMessageHome;
import com.yule.flow.model.FlowMessage;
import com.yule.flow.model.FlowMessageExample;
import com.yule.mq.producer.SystemLogProducer;
import com.yule.query.Query;
import com.yule.system.home.SystemMenuHome;
import com.yule.system.model.SystemLog;
import com.yule.system.model.SystemMenu;
import com.yule.system.model.SystemMenuExample;
import com.yule.system.model.SystemUser;
import com.github.pagehelper.PageInfo;
import com.yule.utils.IpUtils;
import com.yule.vo.LogOperateVo;
import com.yule.utils.UserUtils;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.utils.Collections3;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller("")
public class IndexController extends BaseController {

    private static final Logger logger = Logger.getLogger(IndexController.class);

    @Autowired
    private SystemMenuHome systemMenuHome;

    @Autowired
    private SystemLogProducer systemLogProducer;

    @Autowired
    private FlowMessageHome flowMessageHome;

    @RequestMapping("/loginAuth")
    public String login(@Param("username") String username, @Param("password") String password, RedirectAttributes ra, HttpServletRequest request) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            logger.info("对用户[" + username + "]进行登录验证..验证开始");
            currentUser.login(token);
            logger.info("对用户[" + username + "]进行登录验证..验证通过");
            SystemUser user = UserUtils.getUser(SecurityUtils.getSubject().getPrincipal());
            systemLogProducer.sendLog(new SystemLog(user, LogOperateVo.login.getKey(), null, IpUtils.getIpAddr(request), new Date()));
            return "redirect:/";
        }catch(UnknownAccountException uae){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
            ra.addAttribute("msg", 1);
            return "redirect:/login.jsp";
        }catch(IncorrectCredentialsException ice){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
            ra.addAttribute("msg", 1);
            return "redirect:/login.jsp";
        }catch(LockedAccountException lae){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
            ra.addAttribute("msg", 1);
            return "redirect:/login.jsp";
        }catch(ExcessiveAttemptsException eae){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
            ra.addAttribute("msg", 1);
            return "redirect:/login.jsp";
        }catch(AuthenticationException ae){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
            ra.addAttribute("msg", 1);
            return "redirect:/login.jsp";
        }
    }

    @RequestMapping("/")
    public ModelAndView index(){
        SystemUser user = UserUtils.getUser(SecurityUtils.getSubject().getPrincipal());
        List<SystemMenu> menuList = user.getSystemMenuList();
        ModelAndView mav = new ModelAndView();
        SystemMenuExample systemMenuExample = new SystemMenuExample();
        SystemMenuExample.Criteria criteria = systemMenuExample.createCriteria();
        if (menuList != null) {
            criteria.andMenuTypeEqualTo(1).andIsDelEqualTo(false).andIdIn(Collections3.extractToList(menuList, "id"));
            systemMenuExample.setOrderByClause("seq asc");
            DynamicDataSourceContext.setDBType("default");
            List<SystemMenu> systemMenuList = systemMenuHome.findList(systemMenuExample);
            mav.addObject("systemMenuList", systemMenuList);
        } else {
            List<SystemMenu> systemMenuList = new ArrayList<SystemMenu>();
            mav.addObject("systemMenuList", systemMenuList);
        }
        /*List<SystemMenu> parentMenuList = systemMenuMapper.selectByExample(systemMenuExample);
        systemMenuExample.clear();
        criteria.andPidNotEqualTo(0).andMenuTypeEqualTo(1).andIsDelEqualTo(false);
        systemMenuExample.setOrderByClause("seq asc");
        List<SystemMenu> childMenuList = systemMenuMapper.selectByExample(systemMenuExample);
        for (SystemMenu systemMenu : menuList) {
            if (systemMenu.getPid() == 0) {
                parentMenuList.add(systemMenu);
            } else {
                childMenuList.add(systemMenu);
            }
        }*/
        DynamicDataSourceContext.setDBType(user.getCorpLoginName());
        FlowMessageExample flowMessageExample = new FlowMessageExample();
        flowMessageExample.createCriteria().andCorpIdEqualTo(user.getCorpId())
                .andIsDelEqualTo(false).andReceiveIdEqualTo(user.getId()).andStatusEqualTo(1);
        List<FlowMessage> messageList = flowMessageHome.findList(flowMessageExample);
        mav.addObject("flag", 1);
        if (messageList.size() > 0) {
            mav.addObject("message", 1);
        } else {
            mav.addObject("message", 2);
        }
        //mav.addObject("childMenuList", childMenuList);
        mav.setViewName("../index");
        return mav;
    }

    @RequestMapping("/login")
    public void login(HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        out.flush();
        out.println("<script>");
        out.println("window.top.location.href='/login.jsp'");
        out.println("</script>");
    }

    public static void main(String s[]){
        SimpleHash password = new SimpleHash("md5","1", ByteSource.Util.bytes("abcd"),2);
        System.out.println(password);
    }

    @RequestMapping("/help")
    public ModelAndView help(PageInfo page, Query query){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("system/user/help");
        return mav;
    }

    @RequestMapping(value = "/export/{id:[0-9]+}", method = RequestMethod.GET)
    public void export(@PathVariable("id")Integer id, HttpServletRequest request, HttpServletResponse response) throws WriteException, IOException, BiffException {
        //String path = getStaticPath();
        //path = path.substring(0, path.lastIndexOf("/yule-web/"));
        File source = null;
        if (id == 1) {
            source = new File("/ips_cloud/web/static/help/APQP项目文件管理.docx");
        } else if (id == 2) {
            source = new File("/ips_cloud/web/static/help/IPS-新版FMEA作业指导书0904.docx");
        }
        super.download(source, null, response);
    }
}
